<template>
	<view>
		<form @submit="formSubmit">
			<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
				<image :src="avatarUrl" />
			</button>
			<view class="input-name">
				<text class="name_left">昵称</text>
				<input type="nickname" name="username" class="weui-input" placeholder="请输入昵称" />
			</view>
			<view class="submit-view">
				<button class="submit-Button" form-type="submit">提交</button>
			</view>
		</form>
	</view>
</template>

<script>
	const defaultAvatarUrl = '/static/avater.png'
	export default {
		data() {
			return {
				avatarUrl: defaultAvatarUrl
			}
		},
		methods: {
			gotoMy() {
				uni.navigateBack()
			},
			//提交表单的操作,e.target.value.username
			//获取名字，上传存储区
			formSubmit(e) {
				console.log(e.target.value.username)
				var uuid = new Date().getTime() + Math.random().toString(36).substr(2);
				console.log(uuid); // 1590753224242oqgomgkv7tp
				const url = this.avatarUrl;
				// 获取最后一个"."出现的位置
				const dotIndex = url.lastIndexOf('.');
				// 使用substring()函数从dotIndex开始截取到字符串末尾
				const extension = url.substring(dotIndex);
				console.log(extension); // 输出: "jpeg"
				// 将图片上传至云存储空间
				wx.cloud.uploadFile({
					// 指定上传到的云路径
					cloudPath: 'avatar/' + uuid + extension,
					// 指定要上传的文件的小程序临时文件路径
					filePath: this.avatarUrl,
					// 成功回调
					success: res => {
						console.log('上传成功', res)
						const fileId = res.fileID
						// 获取图片URL
						wx.cloud.getTempFileURL({
							fileList: [fileId],
							success: res => {
								console.log('获取URL成功', res.fileList[0].tempFileURL)
								const imgUrl = res.fileList[0].tempFileURL
								this.avatarUrl = imgUrl
								//将头像的URL和用户的名称信息保存进数据库当中
								wx.cloud.database().collection('user').doc(getApp().globalData
									.userdata._id).update({
									data: {
										avatar: this.avatarUrl,
										nickname: e.target.value.username
									}
								}).then((res) => {
									console.log("数据库更新成功")
									console.log(res.stats)
									//将头像的URL和用户名保存进缓存当中，提升显示的速度
									wx.setStorageSync("avt", this.avatarUrl);
									wx.setStorageSync("nickName", e.target.value.username);
									//转跳到用户页面
									this.gotoMy()
								}).catch(err => {
									console.log(err)
								})
							},
							fail: console.error
						})
					},
				})

			},
			//选中某个头像后的操作
			onChooseAvatar(e) {
				console.log(e.target.avatarUrl)
				this.avatarUrl = e.target.avatarUrl
			}
		}
	}
</script>

<style>
	.avatar-wrapper {
		width: 120rpx;
		height: 120rpx;
		margin-top: 150rpx;
		padding: 0;
	}

	.input-name {
		margin-top: 70rpx;
		height: 80rpx;
		background-color: white;
		text-align: center;
		display: flex;
		align-items: center;
	}

	.submit-Button {
		/* 固定在屏幕底部 */
		position: fixed;
		bottom: 0;
		width: 100%;
	}

	.submit-view {
		width: 100%;
		flex: 1;
	}

	.name_left {
		color: #424242;
		width: 30%;
	}

	image {
		width: 100%;
		height: 120rpx;
	}
</style>
